<?php


namespace app\common\controller;


use app\admin\service\RbacService;
use app\common\exception\ParameterFailedException;
use app\common\model\UsersModel;
use app\common\service\Lang;
use app\common\service\Redis;
use app\common\validate\CommonValidate;
use app\common\validate\UsersValidate;

class CommonController
{
    protected $limit, $page;

    public function __construct()
    {
        $params = self::getParam(['page', 'limit']);
        (new CommonValidate())->goCheck('paginate', $params);
        $this->limit = $params['limit'] ?? '10';
        $this->page  = $params['page'] ?? '1';
    }

    /**
     * @param $params
     * @return bool|string|array
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/7/6
     * @Time: 16:40
     */
    protected static function getParam($params)
    {
        $request = \request()->param();
        if (is_array($params)) {
            $return = [];
            foreach ($params as $item) {
                $example = $request[$item] ?? '';
                if ($example === '') {
                    $example = \request()->header($item);
                }
                if ($example === null) {
                    $return[$item] = null;
                } elseif ($example === 0) {
                    $return[$item] = 0;
                } else {
                    $return[$item] = $example;
                }
            }
            return $return;
        }

        if (is_string($params)) {
            return $request[$params] ?? '';
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \Exception
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/8/15
     * @Time: 17:15
     */
    public function putPassword()
    {
        $permissions = RbacService::checkPermissions('admin');
        $params      = self::getParam(['old_password', 'new_password']);
        (new UsersValidate())->goCheck(__FUNCTION__, $params);

        // 验证账号密码
        $userModel = UsersModel::where('id', $permissions['user_id'])->field('id,password,salt')->find();
        if (!$userModel) {
            throw new ParameterFailedException(['msg' => '用户不存在']);
        }
        if (!decryptPassword($params['old_password'], $userModel->password, $userModel->salt)) {
            throw new ParameterFailedException(['msg' => '用户名与密码不匹配']);
        }

        $cryptRes            = cryptPassword($params['new_password']);
        $userModel->password = $cryptRes['password'];
        $userModel->salt     = $cryptRes['salt'];
        $userModel->save();

        //返回token
        return retJson(Lang::PUTDone);
    }
}